var express = require('express')
var router = express.Router()

// 导入db, 操作数据库
const { getAll, getById, exec } = require('../db')

/* 获取所有公告 */
// router.get('/', async (req, res) => {
//   let sql = `select * from gg_notice `
//   const data = await getAll(sql)
//   res.send({
//     code: 0,
//     message: '获取用户成功',
//     result: data,
//   })
// })

router.get('/', async (req, res) => {
  // 解析请求参数(解构query对象, 提取page和size)
  // - page: 请求第page页的数据
  // - size: 每页size条数据
  const { page, size, notice_content } = req.query

  if (!notice_content) {
    // 根据分页公式, 计算offset偏移量
    let offset = (page - 1) * size

    // 操作数据库
    let sql = `select count(*) as total from gg_notice`
    const obj = await getById(sql)

    var sql1 = `select notice_id, notice_content,notice_time from gg_notice order by notice_time desc limit ${offset}, ${size}` /* desc是降序排列  */
    const data = await getAll(sql1)

    res.send({
      code: 0,
      message: '获取用户成功',
      result: {
        total: obj.total,
        data: data,
      },
    })
  } else {
    // 根据分页公式, 计算offset偏移量
    let offset = (page - 1) * size

    // 操作数据库
    let sql = `select  count(*) as total from gg_notice where notice_content LIKE '%${notice_content}%'`
    const obj = await getById(sql)

    var sql1 = `select notice_id, notice_content,notice_time from gg_notice where notice_content LIKE '%${notice_content}%' order by notice_id asc limit ${offset}, ${size} ` /* desc是降序排列  */
    const data = await getAll(sql1)

    res.send({
      code: 0,
      message: '获取用户成功',
      result: {
        total: obj.total,
        data: data,
      },
    })
  }
})

/* 获取某个公告详情 */
router.get('/:notice_id', async (req, res) => {
  const { notice_id } = req.params
  let sql = `select * from gg_notice where notice_id=${notice_id}`
  const data = await getById(sql)
  res.send({
    result: data,
  })
})

/* 发布公告 */
router.post('/', async (req, res) => {
  const { user_id, notice_content } = req.body
  let sql = `insert into gg_notice (user_id,notice_content) values ('${user_id}','${notice_content}')`
  const data = await exec(sql)
  res.send({
    result: data,
  })
})

/* 删除公告 */
router.delete('/:id', async (req, res) => {
  //解构
  const { id } = req.params
  let sql = `delete from gg_notice where notice_id=${id}`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '删除成功',
    result: data,
  })
})

module.exports = router
